//
//  SSStatus.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/8/1.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SDWebImage

class SSStatus: NSObject {
    // 微博创建时间
    var created_at: String?
    // 微博ID
    var id: Int = 0
    // 微博信息内容
    var text: String?
    // 微博来源
    var source: String? {
        didSet {
            let regex = try! NSRegularExpression(pattern: ">.*?<", options: NSRegularExpressionOptions.DotMatchesLineSeparators)
            if let result = regex.firstMatchInString(source!, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: source!.characters.count)) {
                var range = result.rangeAtIndex(0)
                range.location += 1
                range.length -= 2
                source = (source! as NSString).substringWithRange(range)
            }
        }
    }
    // 微博图片
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            if pic_urls!.count == 0 {
                return
            }
            storedPicURLS = [NSURL]()
            for str in pic_urls! {
                if let urlString = str["thumbnail_pic"] as? String {
                    storedPicURLS?.append(NSURL(string: urlString)!)
                }
            }
        }
    }
    // 临时组
    var storedPicURLS: [NSURL]?
    // 大图URL数组
    var largePicURLS: [NSURL]? {
        if picURLS == nil {
            return nil
        }
        var largePicURLS = [NSURL]()
        for url in picURLS! {
            let urlString = url.absoluteString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
            largePicURLS.append(NSURL(string: urlString)!)
        }
        return largePicURLS
    }
    // 微博图片的URL数组
    var picURLS: [NSURL]? {
        return (retweeted_status == nil) ? storedPicURLS : retweeted_status!.storedPicURLS
    }
    
    // 微博作者的用户信息字段
    var user: SSStatusUser?
    // 被转发的原微博信息字段，当该微博为转发微博时返回
    var retweeted_status: SSStatus?
    // 微博对应的行高
    var rowheight: CGFloat?
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let keys = ["created_at", "id", "text", "source", "picURLS", "user"]
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let userDict = value as? [String: AnyObject] {
                user = SSStatusUser(dict: userDict)
            }
            return
        }
        if key == "retweeted_status" {
            if let retweeted_statusDict = value as? [String: AnyObject] {
                retweeted_status = SSStatus(dict: retweeted_statusDict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    class func loadUserStatus(since_id: Int, max_id: Int, completion: (result: [SSStatus]?, error: NSError?) -> ()) {
        
        SSNetworkTools.sharedNetworkTools.loadUserStatus(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil || result == nil{
                completion(result: nil, error: error)
                return
            }
            // 判断能否得到数组statuses
            if let array = result!["statuses"] as? [[String: AnyObject]]{
                var statuses = [SSStatus]()
                for statusDict in array {
                    statuses.append(SSStatus(dict: statusDict))
                }
                downloadPictures(statuses, completion: completion)
//                completion(result: statuses, error: nil)
            } else {
                completion(result: nil, error: error)
            }
        }
    }
    
    private class func downloadPictures(statuses: [SSStatus], completion: (result: [SSStatus]?, error: NSError?) -> ()) {
        let group = dispatch_group_create()
        var dataLength = 0
        for status in statuses {
            guard let picURLS = status.picURLS else {
                continue
            }
            for url in picURLS {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
                    if image != nil {
                        let data = UIImagePNGRepresentation(image)
                        dataLength += (data?.length)!
                    }
                    
                    dispatch_group_leave(group)
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("dataLength---\(dataLength / 1024)KB")
            completion(result: statuses, error: nil)
        }
    }
}
